/**
 * Copyright (C) 2012  TopicBankEx
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.oc.mba.ui;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.j256.ormlite.dao.Dao;
import com.lurencun.android.support.ui.BackUIActivity;
import com.lurencun.android.support.v2.widget.ViewPager;
import com.oc.mba.AppSetting;
import com.oc.mba.R;
import com.oc.mba.entity.TopicEntity;
import com.oc.mba.presist.DataHelper;
import com.oc.mba.presist.FailureTopic;
import com.oc.mba.presist.Paper;
import com.oc.mba.presist.Practice;
import com.oc.mba.presist.PracticeResult;
import com.oc.mba.presist.Topic;
import com.oc.mba.res.RandomPracticeAdapter;

/**
 * 答题界面
 * @author xiaoyu.wang
 * @date 2012-3-6
 */
public class ExtraTopicActivity extends BackUIActivity {

	
	private DataHelper dataHelper;
	private Context mContext;
	private List<TopicEntity> dataSource = new ArrayList<TopicEntity>();
	/** 开始时间 **/
	private Long startTime;
	/** 完成时间 **/
	private Long endTime;
	
	@Override
	protected void overridePendingTransition(Activity activity){
		activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
	}

	@Override
	protected void onCreateEx(Bundle bundle) {
		
		mContext = this;
		dataHelper = new DataHelper(mContext);
		
		// 加载随即试题
		try {
			List<Topic> topicList = loadTopics();
			for (Topic topic : topicList) {
				dataSource.add(new TopicEntity(topic));
				Log.d("------", "topic:" + topic);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		ViewPager container = (ViewPager) findViewById(R.id.topic_container);
		RandomPracticeAdapter adapter = new RandomPracticeAdapter(this);
		adapter.setData(dataSource);
		adapter.setHandler(handler);
		container.setAdapter(adapter);
		startTime = System.currentTimeMillis();
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case 0:
					handleTopicFinish();
					break;
				case 1:
					break;
				default:
					break;
			}
		}
		
	};
	
	private void handleTopicFinish() {
		boolean allFinish = false;
		for (TopicEntity topicEntity : dataSource) {
			allFinish = topicEntity.isFinish();
		}
		
		if (allFinish) {
			Toast.makeText(mContext, "all topic finished. please see the result.", Toast.LENGTH_LONG).show();
			endTime = System.currentTimeMillis();
			final PracticeResult result = computeResult();
			Log.d("------", result.toString());
			savePractice(result);
			Button viewResultBtn = (Button) findViewById(R.id.topic_finish_btn);
			viewResultBtn.setVisibility(View.VISIBLE);
			viewResultBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("random_practice_result", result);
					Intent mIntent = new Intent();
					mIntent.putExtras(bundle);
					mIntent.setClass(mContext, ResultActivity.class);
					startActivity(mIntent);
					finish();
				}
			});
		}
	}
	
	private void savePractice(PracticeResult result) {
		try {
			Practice practice = new Practice();
			practice.setType(Practice.RANDOM);
			practice.setCorrectCount(result.getCorrectCount());
			practice.setFailureCount(result.getFailureCount());
			practice.setScore(result.getScore());
			practice.setStartTime(result.getStartTime());
			practice.setTimeUsed(result.getTimeUsed());
			getHelper().getPracticeDao().create(practice);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 计算考试结果
	 * 保存错误题目至错题数据库
	 * @return 
	 * 
	 */
	private PracticeResult computeResult() {
		PracticeResult result = new PracticeResult();
		result.setStartTime(new Date(startTime));
		result.setTimeUsed((endTime - startTime) / 1000);
		// 每题得分
		int perScore = 2;
		
		for (TopicEntity topicEntity : dataSource) {
			// 错误
			if (!topicEntity.isCorrect()) {
				// 添加至错题库
				result.setFailureCount(result.getFailureCount() + 1);
				try {
					FailureTopic failure;
					List<FailureTopic> failureTopics = getHelper().getFailureDao().queryBuilder().where().eq("topicId",topicEntity.getTopicId()).query();
					if (failureTopics!=null && failureTopics.size() > 0) {
						failure = failureTopics.get(0);
						failure.setFailureCount(failure.getFailureCount() + 1);
						getHelper().getFailureDao().update(failure);
					}else {
						failure = new FailureTopic();
						failure.setFailureCount(failure.getFailureCount() + 1);
						getHelper().getFailureDao().create(failure);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			// 正确
			else {
				result.setCorrectCount(result.getCorrectCount() + 1);
			}
		}
		result.setScore(perScore * result.getCorrectCount());
		return result;
	}

	@Override
	protected int getContentViewLayoutId() {
		return R.layout.topicex;
	}

	@Override
	protected int getBackButtonResId() {
		return R.id.back_button;
	}

	@Override
	protected boolean isConfirmBack() {
		return true;
	}
	
	@Override
	protected String getTipMessage(){
		return AppSetting.TOPIC_BACK_TIP;
	}
	

	private List<Topic> loadTopics() throws SQLException {
		Dao<Paper, Long> paperDao = getHelper().getPaperDao();
		List<Paper> pList = paperDao.queryForAll();
		List<Topic> topicList = new ArrayList<Topic>();
		for (Paper paper : pList) {
			if (paper!=null && paper.isPurchased() && paper.getTopics()!=null && paper.getTopics().size() > 0) {
				topicList.addAll(paper.getTopics());
			}
		}
		
		return getRandomNum(topicList, 30);
	}

	/**
     * 返回随机数
     * @param list 备选号码
     * @param selected 备选数量
     * @return
     */
    public static List<Topic> getRandomNum(List<Topic> list, int selected) {
        List<Topic> reList = new ArrayList<Topic>();

        Random random = new Random();
        // 先抽取，备选数量的个数
        if (list.size() >= selected) {
            for (int i = 0; i < selected; i++) {
                // 随机数的范围为0-list.size()-1;
                int target = random.nextInt(list.size());
                reList.add(list.get(target));
                list.remove(target);
            }
        } else {
            selected = list.size();
            for (int i = 0; i < selected; i++) {
                // 随机数的范围为0-list.size()-1;
                int target = random.nextInt(list.size());
                reList.add(list.get(target));
                list.remove(target);
            }
        }
      
        return reList;
    }
    

	private DataHelper getHelper() {
		return dataHelper;
	}
}
